/**
 * @Title: idesk_data_ctrl.js
 * @Description: 结算首页
 * Copyright: Copyright (c) 2014 
 * Company:中国平安
 *
 * @Project HIMS-FWA
 * @author QIANDUO875
 * @date 2014年9月22日 下午2:44:57
 * @version V1.0
 */
;
(function(){
	'use strict';
	var app = angular.module('fwa.mainApp');
	
	app.controller('IDeskDataCtrl',
			['$scope','IDeskDataService','$modal','Modal','$http','BaseURL','$state','FwaTabsetService','CommunityService',
	                                function($scope,IDeskDataService,$modal,Modal,$http,baseUrl,$state,FwaTabsetService,CommunityService){
		
		/*********************************************************
		 * 
		 * Scope & Variables Init
		 * 
		 */
		$scope.communityService = CommunityService;
		CommunityService.initCodeListDatas();
		
		//弹窗,指标查询
		$scope.openKpiModal = function(){
			if (IDeskDataService.result.state != "0") {
				Modal.alert(IDeskDataService.result.msg);
				return false;
			}
			var endDate = $scope.date;
			if(null!=endDate && ""!=endDate){
                var dateReg =/^\d{4}-\d{2}$/;
                if(!dateReg.test(endDate)){
                    Modal.alert("结算分析时间格式错误");
                    return false;
                }
            }else{
                Modal.alert("结算分析时间不能为空");
                return false;
            }
			 var modalInstance = $modal.open({
			      templateUrl: baseUrl+'views/hcpms/achievements/settlement/kpiClassModal.html',
			      backdrop:'static',
				  size:'sm',
				  controller: function($scope, $http,$modalInstance,Modal,IDeskDataService,CommunityService){
					  $scope.kpiParamList = {};
					  $scope.communityService = CommunityService;
					  $scope.$watch('communityService.kpiTypeDatas',function(v){
						  if(v){
							  $scope.kpiClassificationList = v;
							  //初始化下拉框值
							  $scope.kpiParamList.kpiClassification = v[0].code;
					          setKpiList();
						  }
					  });
					  
					  //选中指标分类
					  $scope.changeKpiList = function(){
			        	 setKpiList();
			        	 $scope.kpiParamList.indicatorSelected = null;
			          };
			          var setKpiList = function(){
							  IDeskDataService.queryKpi($scope.kpiParamList.kpiClassification).success(function(res){
								  $scope.areaList = res.list;
							  });
			          };
			          
			          
					  $scope.onOk = function() {
						  $modalInstance.close();
					  }
					  $scope.confirm = function() {
						  if ($scope.kpiParamList.indicatorSelected) {
							  FwaTabsetService.selectTab('settleAnalyse.regionView',{indicator:$scope.kpiParamList.indicatorSelected||'',view:'',startDate: '',endDate: endDate||''}, false);
							  $modalInstance.close();
						  }else{
							  Modal.alert("请选中一个指标名称");
						  }
						
					  }
				  }
			 });
		}
		//弹窗,医疗机构
		$scope.openhospitalModal = function(){
			if (IDeskDataService.result.state != "0") {
				Modal.alert(IDeskDataService.result.msg);
				return false;
			}
			var endDate = $scope.date;
			if(null!=endDate && ""!=endDate){
                var dateReg =/^\d{4}-\d{2}$/;
                if(!dateReg.test(endDate)){
                    Modal.alert("结算分析时间格式错误");
                    return false;
                }
            }else{
                Modal.alert("结算分析时间不能为空");
                return false;
            }
			//获取医疗机构级别
			 var modalInstance = $modal.open({
			      templateUrl: baseUrl+'views/hcpms/achievements/settlement/hospitalModal.html',
			      backdrop:'static',
				  size:'sm',
				  controller: function($scope, $http,$modalInstance,Modal,IDeskDataService,CommunityService){
					  
					  $scope.hospitalParamList = {};
					  $scope.communityService = CommunityService;
					  $scope.hospitalClassificationList = [];
					  $scope.$watch('communityService.orgLevelDatas',function(v){
						  if(v){
							  angular.forEach(v,function(data,index){
									if (data.code != '6') {
										 $scope.hospitalClassificationList.push(data);
									}
								});
							 
							  //初始化下拉框值
					          $scope.hospitalParamList.hospitalClassification = v[0].code;
					          setHospitalList();
						  }
					  });
					 //选中机构等级事件
					  $scope.changehospitalList = function(){
			        	  if($scope.hospitalParamList.hospitalClassification){
			        		  setHospitalList();
			        	  }else{
			        		  $scope.medicalOrgInfoList = [];
			        	  }
			        	  $scope.hospitalParamList.organiz = null;
			          };
			          //根据等级获取医疗机构信息
			         var setHospitalList = function(){
			        	 var params = {
				    		 orgLevelList: $scope.hospitalParamList.hospitalClassification
				    	 };
						  IDeskDataService.queryHospital(params).success(function(response, status, headers, config){
							  $scope.medicalOrgInfoList = response.medicalOrgList;
						});
			          };
			          $scope.kpiParamList = {};
					  $scope.$watch('communityService.kpiTypeDatas',function(v){
						  if(v){
							  $scope.kpiClassificationList = v;
							  //初始化下拉框值
							  $scope.kpiParamList.kpiClassification = v[0].code;
					          setKpiList();
						  }
					  });
					  
					  //选中指标分类
					  $scope.changeKpiList = function() {
			        	 setKpiList();
			        	 $scope.kpiParamList.indicatorSelected = null;
			          };
			          var setKpiList = function(){
						  IDeskDataService.queryKpi($scope.kpiParamList.kpiClassification).success(function(res){
							  $scope.areaList = res.list;
						  });
			          };
			          //关闭事件
					  $scope.onOk = function() {
						 $modalInstance.dismiss();
					  }
					  
					  //确定事件
					  $scope.confirm = function() {
						  if (!$scope.hospitalParamList.organiz) {
							  Modal.alert("请选中一个医疗机构");
							  return false;
						  }
						  if (!$scope.kpiParamList.indicatorSelected) {
							  Modal.alert("请选中一个指标名称");
							  return false;
						  }
						  FwaTabsetService.selectTab('settleAnalyse.orgView',{indicator:$scope.kpiParamList.indicatorSelected||'',view:'org',startDate:'',endDate:endDate||'',dept:'',id:$scope.hospitalParamList.organiz||''}, false);
						  $modalInstance.dismiss();
					  }
			       }
			 });
		}
		
		//分布图Option获取
		function getPieSeries(option, data) {
			return [{
				name:option.text,
				type:'pie',
				radius:'47%',
				center:['52%','57%'],
				data:data,
				itemStyle:{
					normal:{
						label:{
							formatter:'{b}\n{c}\n({d}%)'
						}
					}
				}
			}];
		}
		function getPieOptin(option) {
			return {
				type:'radius',
				trigger:'item',
				text:option.text,
				grid:{
					x:0,
					y:0,
					x2:0,
					y2:0,
					borderColor:'#fff'
				},
				legendData:null,
				legendAlign:'center',
				formatter:'{b}:{c}({d}%)',
				color:option.color,
				series:getPieSeries(option, [])
			};
		}
		//费用分布图
		$scope.feeChart = getPieOptin({
			text:'医疗费用分布(万元)',
			color:['#81bfdf','#0c77af']
		});
		
		//人次分布
		$scope.visitorsChart = getPieOptin({
			text:'诊疗人次分布(万次)',
			color:['#81bfdf','#0c77af']
		});
		
		/*********************************************************
		 * 
		 * Event Handler
		 * 
		 */
		//选中日期加载
		function changeDateFeeInfo() {
			//获取费用信息
			IDeskDataService.getFeeInfos($scope.date).success(function(res){
				if (res.state == "0") {
					$scope.feeInfo = res.feeInfo;
					$scope.feeChart.series = getPieSeries({text:'医疗费用分布'},[{
						value:res.feeDistribution.hosp, name:'住院 '
					},{
						value:res.feeDistribution.out, name:'门诊 '
					}]);;
					
					$scope.visitorsChart.series = getPieSeries({text:'诊疗人次分布'},[{
						value:res.visitorsDistribution.hosp, name:'住院 '
					},{
						value:res.visitorsDistribution.out, name:'门诊 '
					}]);
					$scope.$broadcast('ideskData.dateChange',$scope.date);
				}
				else {
					IDeskDataService.result = res;
					Modal.alert(res.msg);
				}
			});
			
		}
		
		//默认日期 当前日期的前一个月
		CommunityService.initDate("yyyy-MM").success(function(res) {
			$scope.date = CommunityService.lastMonth(res.formatDate);
			changeDateFeeInfo();
		});
		//监听操作日期控件
		$scope.$on('fwaDatetime.change', function(e,v){
			if(v){
				changeDateFeeInfo();
			}
		});
		
		//查看趋势
		$scope.queryFeeView = function() {
			var endDate = $scope.date;
            if(null!=endDate && ""!=endDate){
                var dateReg =/^\d{4}-\d{2}$/;
                if(!dateReg.test(endDate)){
                    Modal.alert("结算分析时间格式错误");
                    return false;
                }
            }else{
                Modal.alert("结算分析时间不能为空");
                return false;
            }
			if (IDeskDataService.result.state != "0") {
				Modal.alert(IDeskDataService.result.msg);
				return false;
			}
			FwaTabsetService.selectTab('feeView.detail',{
				indicator:'KPI0001',
				hospType:'',
				date:$scope.date
			},false);
		}
		
	}]).
	
	//各种费用Ctrl
	controller('FeeCtrl', ['$scope','$state','IDeskDataService','FwaTabsetService','Modal',function($scope,$state,IDeskDataService,FwaTabsetService,Modal){
		
		/******************************************************
		 * 
		 * Const
		 * 
		 */
		var TYPE_HOSP = 'hosp',
			TYPE_ALL = 'all',
			TYPE_OUT = 'out',
			TAB_Fee = 'fee',
			TAB_FeeBudget = 'budget',
			TAB_FeePercentage = 'percentage',
			TAB_FeeDistribution = 'distribution';
		
		
		/*********************************************************
		 * 
		 * Scope & Variables Init
		 * 
		 */
		var feeData = null;
		
		//初始化费用Tab
		$scope.tabs = [
		    {label:'医疗费用',id: TAB_Fee},
		    {label:'医疗费用预拨',id:TAB_FeeBudget},
		    {label:'医保费用占比',id:TAB_FeePercentage},
		    {label:'费用分布',id:TAB_FeeDistribution}
		];
		
		$scope.selectedTab = $scope.tabs[0]; 	//选中tab
		$scope.typeSelected = TYPE_ALL;				//选中的数据类型
		
		
		//费用分布表
		$scope.bar = {
			type:'bar',
			trigger:'axis',
			text:'',
			subtext:'',
			grid:{
				x:50,
				y:10,
				x2:17,
				y2:30,
				borderColor:'#eee'
			},
			legendData:[],
			legendAlign:'center',
			magicType:false,
			axisData:['三级','二级','一级'],
			axisFormatter:'',
//			formatter:'({d/1000})',
			color:['#dd4814'],
			series:[]
		};
		
		var cellTemp = '<span class="pull-right" ng-bind="(data.over * 100).toFixed(2)+\'%\'" \
			ng-class="{\'text-warning\':data.over>=0.3 && data.over<0.8,\
			\'text-danger\':data.over>=0.8}"></span>';
		
		//table定义
		$scope.tableColumns = [
		    {label:'机构等级', width:'25%', map:'orgLevel'},
		    {label:'全部', width:'25%', map:'all'},
    		{label:'住院', width:'25%', map:'hosp'},
		    {label:'门诊', width:'25%', map:'out'}]
		
		$scope.tableDatas = [];

		
		/*********************************************************
		 * 
		 * Event Handler
		 * 
		 */
		function refreshFeeSeries() {
			var data = [];
			var datas = []; //费用分布
			if (!feeData
			   ||!feeData[$scope.selectedTab.id]
			   ||!feeData[$scope.selectedTab.id][$scope.typeSelected] 
			   || feeData[$scope.selectedTab.id][$scope.typeSelected] == null
			   || feeData[$scope.selectedTab.id][$scope.typeSelected] == '') {
				$scope.bar.series = [];
				return;
			}
			data = feeData[$scope.selectedTab.id][$scope.typeSelected];
			if($scope.selectedTab.id == TAB_FeeDistribution){
				var dataOther = [],
					dataKPI0005 = [],
					dataKPI0008 = [],
					dataKPI0009 = [],
					label = ['药费占比','检查化验费占比','手术费占比','其他'];
				
				for(var i =0; i<data.length; i++){
					datas.push(data[i]);
					if (data[i].other) {
						dataOther = data[i].other;
					}
					else if (data[i].KPI0005) {
						dataKPI0005 = data[i].KPI0005;
					}
					else if (data[i].KPI0008) {
						dataKPI0008 = data[i].KPI0008;
					}
					else if (data[i].KPI0009) {
						dataKPI0009 = data[i].KPI0009;
					}
				}
				$scope.bar.color = ['#dd4814',  '#FF855A','#3ca5d0','#006397'];
				
				$scope.bar.axisFormatter = '{value}%';
				$scope.bar.grid ={
						x:50,
						y:25,
						x2:17,
						y2:30,
						borderColor:'#eee'
					};
				$scope.bar.legendData = label;
				$scope.bar.legendAlign = 'center';
				$scope.bar.series = [{
		            name:label[0],
		            type:'bar',
		            barWidth:15,
		            data:[dataKPI0005.l3, dataKPI0005.l2, dataKPI0005.l1]
		        },{
		            name:label[1],
		            type:'bar',
		            barWidth:15,
		            data:[dataKPI0008.l3, dataKPI0008.l2, dataKPI0008.l1]
		        },{
		            name:label[2],
		            type:'bar',
		            barWidth:15,
		            data:[dataKPI0009.l3, dataKPI0009.l2, dataKPI0009.l1]
		        },{
		            name:label[3],
		            type:'bar',
		            barWidth:15,
		            data:[dataOther.l3, dataOther.l2, dataOther.l1]
		        }];
			}
			else {
				$scope.bar.legendData = [];
				
				if ($scope.selectedTab.id == TAB_FeePercentage) {
					$scope.bar.grid = {
							x:40,
							y:10,
							x2:17,
							y2:30,
							borderColor:'#eee'
						};
					$scope.bar.axisFormatter = '{value}%';
				}
				else {
					$scope.bar.grid = {
							x:55,
							y:10,
							x2:17,
							y2:30,
							borderColor:'#eee'
						};
					$scope.bar.axisFormatter = '{value}万';
				}
				$scope.bar.series = [{
		            name:$scope.selectedTab.label,
		            type:'bar',
		            barWidth:50,
		            data:[data.l3, data.l2, data.l1],
		            itemStyle:{
		            	normal:{
		            		label:{
			            		show:true,
			            		position:'inside'
			            	}
			            }
		            }
		        }];
			}
		}
		
		function refreshTableData() {
			if (!feeData 
				|| !feeData[$scope.selectedTab.id] 
				|| !feeData[$scope.selectedTab.id].table 
				|| feeData[$scope.selectedTab.id].table == null 
				|| feeData[$scope.selectedTab.id].table == '') {
				$scope.tableDatas = [];
				return ;
			}
			var datas = [] ,flag = false;
			angular.forEach(feeData[$scope.selectedTab.id].table,function(tableData,index){
				if(tableData.list){
					flag = true;
					angular.forEach(tableData.list,function(data,index){
						if(index == 0){
							data.rowSpan = tableData.list.length;
							data.orgLevel = tableData.orgLevel;
						}
						datas.push(data);
					});
				}else{
					tableData.rowSpan = 1;
					datas.push(tableData);
				}
			});
			if (flag) {
				$scope.tableDatas = datas;
			}
			else {
				//预拨 以及费用 以万元为单位
				if ((isfee && $scope.selectedTab.id == TAB_Fee)) {
					isfee = false;
					$scope.tableDatas = toFixedDatas(feeData[$scope.selectedTab.id].table);
				} 
				else if (isFeeBudget
						&& $scope.selectedTab.id == TAB_FeeBudget) {
					isFeeBudget = false;
					$scope.tableDatas = toFixedDatas(feeData[$scope.selectedTab.id].table);
				}
				else {
					$scope.tableDatas = feeData[$scope.selectedTab.id].table;
				}
			}
		}
		/*以万元为单位*/
		function toFixedDatas(datas) {
			angular.forEach(datas,function(data,index){
				data.all = (parseFloat(data.all||0)/10000).toFixed(2);
				data.hosp = (parseFloat(data.hosp||0)/10000).toFixed(2);
				data.out = (parseFloat(data.out||0)/10000).toFixed(2);
			});
			return datas;
		}
		//取万元只执行一次
		var isfee = true,isFeeBudget = true;
		//月份变化响应
		$scope.$on('ideskData.dateChange', function(e,v){
			
			$scope.typeSelected = TYPE_ALL;
			// bar数据
			IDeskDataService.getOrgFeeDataGroup(v).
				success(function(res){
					if (res.state == "0") {
						isfee = true;
						isFeeBudget = true;
						feeData = res;
						refreshFeeSeries();
						refreshTableData();
					}
					else {
						Modal.alert(res.msg);
					}
				});
		});
		$scope.kpiMap = {
				other:'其他',
				KPI0005:'药费占比',
				KPI0008:'检查化验费占比',
				KPI0009:'手术费占比'
		};
		//费用tab
		$scope.tabClick = function(tab) {
			if (IDeskDataService.result.state != "0") {
				Modal.alert(IDeskDataService.result.msg);
				return false;
			}
			if('distribution'==tab.id){
				$scope.tableColumns = [
				           		    {label:'机构等级', width:'20%', map:'orgLevel'},
				           		    {label:'指标名称', width:'20%', map:'kpiCode'},
				           		    {label:'全部', width:'20%', map:'all'},
				               		{label:'住院', width:'20%', map:'hosp'},
				           		    {label:'门诊', width:'20%', map:'out'}]
			}else{
				$scope.tableColumns = [
				           		    {label:'机构等级', width:'25%', map:'orgLevel'},
				           		    {label:'全部', width:'25%', map:'all'},
				               		{label:'住院', width:'25%', map:'hosp'},
				           		    {label:'门诊', width:'25%', map:'out'}]
			}
			$scope.selectedTab = tab;
			$scope.typeSelected = TYPE_ALL;
			refreshFeeSeries();
			refreshTableData();
		}
		
		//数据类型切换,总住门
		$scope.typeClick = function(type) {
			if (IDeskDataService.result.state != "0") {
				Modal.alert(IDeskDataService.result.msg);
				return false;
			}
			$scope.typeSelected = type;
			refreshFeeSeries();
		}
		
		//查看趋势
		$scope.queryFeeView = function() {
			 var endDate = $scope.date;
	            if(null!=endDate && ""!=endDate){
	                var dateReg =/^\d{4}-\d{2}$/;
	                if(!dateReg.test(endDate)){
	                    Modal.alert("结算分析时间格式错误");
	                    return false;
	                }
	            }else{
	                Modal.alert("结算分析时间不能为空");
	                return false;
	            }
			if (IDeskDataService.result.state != "0") {
				Modal.alert(IDeskDataService.result.msg);
				return false;
			}
			var indicator = '';//指标编号
			var hospType = $scope.typeSelected;//all.总、hosp.住、out.门
			if($scope.selectedTab.id == TAB_Fee){
				indicator = 'KPI0001';//医疗费用
			}else if($scope.selectedTab.id == TAB_FeeBudget){
				indicator = 'KPI0003';//医疗费用预拨
			}else if($scope.selectedTab.id == TAB_FeePercentage){
				indicator = 'KPI0002';//医保费用占比
			}
			if($scope.selectedTab.id == TAB_FeeDistribution){
				FwaTabsetService.selectTab('costCover.situation',{
					date:$scope.date
				 	},false);
			}else{
				 FwaTabsetService.selectTab('feeView.detail',{
						indicator: indicator,
						hospType: hospType,
						date: $scope.date
					 	},false);
			}
		}
	}]);
})();